import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path;

class VideoPickerUtil {
  static final ImagePicker _picker = ImagePicker();

  /// 从相册选择视频
  static Future<String?> pickVideoFromGallery() async {
    try {
      final XFile? video = await _picker.pickVideo(
        source: ImageSource.gallery,
        maxDuration: const Duration(minutes: 5), // 限制视频长度为5分钟
      );

      if (video != null) {
        // 将视频复制到应用目录
        final String savedPath = await _saveVideoToAppDirectory(video);
        return savedPath;
      }
      return null;
    } catch (e) {
      debugPrint('选择视频失败: $e');
      return null;
    }
  }

  /// 录制视频
  static Future<String?> recordVideo() async {
    try {
      final XFile? video = await _picker.pickVideo(
        source: ImageSource.camera,
        maxDuration: const Duration(minutes: 3), // 限制录制时长为3分钟
      );

      if (video != null) {
        // 将视频保存到应用目录
        final String savedPath = await _saveVideoToAppDirectory(video);
        return savedPath;
      }
      return null;
    } catch (e) {
      debugPrint('录制视频失败: $e');
      return null;
    }
  }

  /// 显示视频选择对话框
  static Future<String?> showVideoPickerDialog(BuildContext context) async {
    final result = await showDialog<String>(
      context: context,
      builder: (BuildContext dialogContext) {
        return AlertDialog(
          title: const Text('选择视频'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              ListTile(
                leading: const Icon(Icons.photo_library),
                title: const Text('从相册选择'),
                onTap: () {
                  Navigator.of(dialogContext).pop('gallery');
                },
              ),
              ListTile(
                leading: const Icon(Icons.videocam),
                title: const Text('录制视频'),
                onTap: () {
                  Navigator.of(dialogContext).pop('camera');
                },
              ),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(dialogContext).pop(),
              child: const Text('取消'),
            ),
          ],
        );
      },
    );

    // 根据用户选择执行相应操作
    if (result == 'gallery') {
      return await pickVideoFromGallery();
    } else if (result == 'camera') {
      return await recordVideo();
    }

    return null;
  }

  /// 将视频保存到应用目录
  static Future<String> _saveVideoToAppDirectory(XFile video) async {
    try {
      // 获取应用文档目录
      final Directory appDir = await getApplicationDocumentsDirectory();
      final Directory videoDir = Directory('${appDir.path}/videos');

      // 创建视频目录（如果不存在）
      if (!await videoDir.exists()) {
        await videoDir.create(recursive: true);
      }

      // 生成唯一的文件名
      final String fileName =
          '${DateTime.now().millisecondsSinceEpoch}${path.extension(video.path)}';
      final String savedPath = '${videoDir.path}/$fileName';

      // 复制文件
      final File sourceFile = File(video.path);
      await sourceFile.copy(savedPath);

      return savedPath;
    } catch (e) {
      debugPrint('保存视频失败: $e');
      rethrow;
    }
  }

  /// 删除视频文件
  static Future<bool> deleteVideo(String videoPath) async {
    try {
      final File videoFile = File(videoPath);
      if (await videoFile.exists()) {
        await videoFile.delete();
        return true;
      }
      return false;
    } catch (e) {
      debugPrint('删除视频失败: $e');
      return false;
    }
  }

  /// 获取视频文件大小（字节）
  static Future<int> getVideoFileSize(String videoPath) async {
    try {
      final File videoFile = File(videoPath);
      if (await videoFile.exists()) {
        return await videoFile.length();
      }
      return 0;
    } catch (e) {
      debugPrint('获取视频文件大小失败: $e');
      return 0;
    }
  }

  /// 格式化文件大小显示
  static String formatFileSize(int bytes) {
    if (bytes < 1024) {
      return '$bytes B';
    } else if (bytes < 1024 * 1024) {
      return '${(bytes / 1024).toStringAsFixed(1)} KB';
    } else if (bytes < 1024 * 1024 * 1024) {
      return '${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB';
    } else {
      return '${(bytes / (1024 * 1024 * 1024)).toStringAsFixed(1)} GB';
    }
  }

  /// 检查视频文件是否存在
  static Future<bool> videoExists(String videoPath) async {
    try {
      if (videoPath.startsWith('http')) {
        // 网络视频，假设存在（实际应用中可以发送HEAD请求检查）
        return true;
      } else {
        final File videoFile = File(videoPath);
        return await videoFile.exists();
      }
    } catch (e) {
      debugPrint('检查视频文件失败: $e');
      return false;
    }
  }

  /// 清理应用视频目录中的旧文件
  static Future<void> cleanupOldVideos({int maxAgeInDays = 30}) async {
    try {
      final Directory appDir = await getApplicationDocumentsDirectory();
      final Directory videoDir = Directory('${appDir.path}/videos');

      if (await videoDir.exists()) {
        final List<FileSystemEntity> files = videoDir.listSync();
        final DateTime cutoffDate = DateTime.now().subtract(
          Duration(days: maxAgeInDays),
        );

        for (final FileSystemEntity file in files) {
          if (file is File) {
            final FileStat stat = await file.stat();
            if (stat.modified.isBefore(cutoffDate)) {
              await file.delete();
              debugPrint('删除旧视频文件: ${file.path}');
            }
          }
        }
      }
    } catch (e) {
      debugPrint('清理旧视频文件失败: $e');
    }
  }
}
